package com.lgd.factoryattendance.Service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.lgd.factoryattendance.R;


import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * @Author lgd
 * @Date 2024/3/8 15:13
 * 前台保活  前台服务
 */
public class KeepLiveService extends Service {

    private TimerTask task;
    private Timer timer;
    private Intent sevice;

    @Override
    public void onCreate() {
        super.onCreate();
        if (task != null) {
            task.cancel();
            task = null;
        }
        task = createVideoSchedulerTimer();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        long delay = 1500;      // 表示延迟
        long intevalPeriod = 2 * 1000;    // 再次调用时间
        timer.schedule(task, delay, intevalPeriod);   // 执行循环任务
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        if (intent == null) {
            startServices();
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "123")
                .setSmallIcon(R.mipmap.logo)
                .setContentTitle("前台服务通知") // 更具体的标题
                .setContentText("应用正在前台运行以保持活跃") // 更详细的描述
                .setWhen(System.currentTimeMillis()) // 时间戳
                .setAutoCancel(true)                 //  设置点击通知后自动清除通知
                .setPriority(NotificationCompat.PRIORITY_DEFAULT); // 设置通知优先级
        Notification notification = builder.build();
        //设置通知默认效果
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        startForeground(1, notification);
        return Service.START_STICKY;
    }

    private void startServices() {
        stopSelf();
        if (sevice == null)
            sevice = new Intent(this, KeepLiveService.class);
        startService(sevice);
    }

    private TimerTask createVideoSchedulerTimer() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                //判断程序是否在运行
//                boolean isRunning = isServiceStarted(getApplicationContext(), "com.lgd.factoryattendance");
//                //没有运行就开启他
//                if (!isRunning) {
//                    Log.e("MyTestService", "程序未开启============");
////下面getLaunchIntentforPackage()里面的参数是程序的bao名，也就是，build.gradle里面的applicationId
//                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.lgd.factoryattendance");
//                    startActivity(intent);
//                }
//                else {
//                    Log.e("MyTestService", "========程序已经运行了==========");
//                }
                // 判断 网络 状态
//                boolean isTrueOrFalse = NetStateUtils.isNetworkOnline2();
//                if (isTrueOrFalse){
//                    Log.e("网络状态","----OK------");
//                }else {
//                    Log.e("网络状态","----No------");
//                }

            }
        };
        return timerTask;
    }

    /**
     * 检测一个android程序是否在运行
     *
     * @param context
     * @param PackageName
     * @return
     */
    public static boolean isServiceStarted(Context context, String PackageName) {
        boolean isStarted = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(PackageName) && info.baseActivity.getPackageName().equals(PackageName)) {
                isStarted = true;
                break;
            }
        }
        return isStarted;
    }

    @Override
    public void onLowMemory() {
        startServices();
        super.onLowMemory();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (task != null) {
            task.cancel();
            task = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }

}
